<?php
declare (strict_types=1);

namespace app\common\helper\util;

use Exception;

class Tool
{
    /**
     * 时间转为字符串时间 秒->天时分秒
     *
     * @static
     * @param      $seconds      时间秒
     * @param      $parseToColon 是否解析成分号格式
     * @param bool $auto         是否自动简化格式
     * @return string
     */
    public static function secsToStr($seconds, $parseToColon = false, bool $auto = false): string
    {
        $leftsecond = intval($seconds);
        if ($parseToColon) {
            return Tool::secsToColonStr($seconds);
        }
        $day1   = sprintf('%02d', floor($leftsecond / (60 * 60 * 24)));
        $hour   = sprintf('%02d', floor(($leftsecond - $day1 * 24 * 60 * 60) / 3600));
        $minute = sprintf('%02d', floor(($leftsecond - $day1 * 24 * 60 * 60 - $hour * 3600) / 60));
        $second = sprintf('%02d', floor($leftsecond - $day1 * 24 * 60 * 60 - $hour * 3600 - $minute * 60));
        if ($auto) {
            // 自动格式化
            $day1   = intval($day1);
            $hour   = intval($hour);
            $minute = intval($minute);
            if ($seconds < 3600) {
                // 1小时内: 显示X分钟
                return "{$minute}分钟";
            } else if ($seconds < 86400) {
                // 1天内: 显示X小时X分钟
                return "{$hour}小时{$minute}分钟";
            } else {
                // 大于1天: 显示X天X小时X分钟
                return "{$day1}天{$hour}小时{$minute}分钟";
            }
        } else {
            // 是否含有天数
            if ($day1 != '00') {
                return "{$day1}天{$hour}时{$minute}分{$second}秒";
            } else {
                return "{$hour}时{$minute}分{$second}秒";
            }
        }
    }

    /**
     * 时间转为字符串格式,以冒号连接
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-08-18
     *
     * @param    [type]                         $seconds [description]
     */
    public static function secsToColonStr($seconds): string
    {
        $leftsecond = intval($seconds);
        if ($leftsecond <= 0) {
            return '00:00';
        } else if ($leftsecond < 60) {
            return sprintf('00:00:%02d', $leftsecond % 60);
        } else if ($leftsecond < 3600) {
            return sprintf('00:%02d:%02d', floor($leftsecond / 60), $leftsecond % 60);
        } else {
            return sprintf('%02d:%02d:%02d', floor($leftsecond / 3600), floor($leftsecond % 3600 / 60), $leftsecond % 60);
        }
    }

    /**
     * 时长转为秒数
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-08-25
     *
     * @param string $str [description]
     */
    public static function strToSecond(string $str)
    {
        $parsed = date_parse($str);

        return $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
    }

    /**
     *
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/1/25
     *
     * @static
     * @param array $datas
     * @param bool  $unlimit
     * @return array[]
     */
    public static function parseToSelectOpions(array $datas, bool $unlimit = true): array
    {

        $options = [];
        if ($unlimit) {
            $options[] = ['title' => '不限制', 'value' => -1];
        }
        foreach ($datas as $value => $title) {
            $options[] = [
                'title' => $title,
                'value' => $value
            ];
        }

        return $options;
    }

    /**
     * 加密ID
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/3/30
     *
     * @static
     * @param $id
     * @return string
     * @throws Exception
     */
    public static function encodeId($id): string
    {
        $id        = (string)$id;
        $length    = strlen($id);
        $snowflake = new SnowFlake();
        $codestr   = $id . $snowflake->nextId();
        $encodestr = sha1($codestr);
        // id的长度
        $code = $length;
        // 截取占位字符
        $code .= substr($encodestr, 5, 16 - $length);
        // 拼装id
        $code .= $id;
        // 截取16位填充字符
        $code .= substr($encodestr, -16 - $length, 16);

        return $code;
    }

    /**
     * 解密ID
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/3/30
     *
     * @static
     * @param string $string
     * @return int
     */
    public static function decodeId(string $string): int
    {
        $length = strlen($string);
        // 超出长度,即为字符串长度的数字
        $overLength = $length - 32;
        $idLength   = (int)substr($string, 0, $overLength);
        $id         = substr($string, 16 - $idLength + $overLength, $idLength);

        return (int)$id;
    }

    /**
     * 过滤html标签
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/4/1
     *
     * @static
     * @param string $string
     * @return string
     */
    public static function filterHtml(string $string): string
    {
        $string = strip_tags($string);
        $string = str_replace('&nbsp;', ' ', $string);

        return str_replace('&', '&amp;', $string);
    }

    /**
     * 匹配html中的图片地址
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/4/1
     *
     * @static
     * @param string $html
     * @return array|mixed
     */
    public static function getImagesFromHtml(string $html)
    {
        preg_match_all('/<img.*?src="(.*?)".*?\/?>/i', $html, $match);

        if ($match) {
            return $match[1];
        }

        return [];
    }

    /**
     * 阿拉伯数字转大写
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/4/1
     *
     * @static
     * @param int $number
     * @return string
     * @TODO 暂时只支持100以内
     */
    public static function number2chinese(int $number): string
    {

        $arr = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
        $n   = (string)$number;
        if (strlen($n) == 1) {
            $result = $arr[$n];
        } else {
            if ($n == 10) {
                $result = '十';
            } else {
                if ($n < 20) {
                    $result = '十';
                } else {
                    $result = $arr[substr($n, 0, 1)] . '十';
                }
                if (substr($n, 1, 1) != '0') {
                    $result .= $arr[substr($n, 1, 1)];
                }
            }
        }

        return $result;


    }

    /**
     * 获取域名，不包含http(s)://
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 23/03/10
     *
     * @static
     * @param $url
     * @return array|false|string|string[]|null
     */
    public static function pregDomain($url)
    {
        $url = preg_replace('(^https?://)', '', $url);
        $pos = strpos($url, '/');

        return $pos ? substr($url, 0, $pos) : $url;
    }

    /**
     * 带单位的文件大小字符串转换成字节数
     *
     * @param $Size
     * @return float|int
     */
    public static function stringSizeToBytes($size)
    {
        $size = strtolower($size);
        $unit = preg_replace('/[^a-z]/', '', $size);

        $value = str_replace($unit, '', $size);//preg_replace('/[^0-9]/', '', $size); //intval();

        $units = [
            'b'  => 0,
            'kb' => 1,
            'mb' => 2,
            'm'  => 2,
            'gb' => 3,
            'tb' => 4
        ];

        $exponent = $units[$unit] ?? 0;

        return ceil($value * pow(1024, $exponent));
    }

}
